package testDataGenerator.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Element;

import testDataGenerator.model.exception.InvalidGenerationOptionException;

public class DataColumn {
	private final String name;
	private DataType dataType;
	private boolean isPrimarykey;
	private boolean isForeignKey;
	private GenerationMethod dataGenerationMethod;
	private GenerationMethodFactory generationMethodFactory;
	private DataTypeFactory dataTypeFactory;
	private String[] data;

	public DataColumn(Element element,
			GenerationMethodFactory generationMethodFactory,
			DataTypeFactory dataTypeFactory) {
		this.name = element.attributeValue("name");
		this.generationMethodFactory = generationMethodFactory;
		this.dataTypeFactory = dataTypeFactory;
		for (Iterator it = element.elementIterator(); it.hasNext();) {
			Element item = (Element) it.next();
			String name = item.getName();
			if (name.equals("dataType")) {
				this.dataType = this.dataTypeFactory.createDataType(item
						.getStringValue());
			}
			if (name.equals("primaryKey")) {
				if (item.getStringValue().equals("true"))
					this.isPrimarykey = true;
				else
					this.isPrimarykey = false;
			}
			if (name.equals("foriegnKey")) {
				if (item.getStringValue().equals("true"))
					this.isForeignKey = true;
				else
					this.isForeignKey = false;
			}
			if (name.equals("dataGeneration"))
				this.dataGenerationMethod = getGenerationMethod(item);
		}
	}

	private GenerationMethod getGenerationMethod(Element element) {
		return generationMethodFactory.createMethod(element, this.dataType
				.getName(), this.dataTypeFactory);
	}

	public GenerationMethod getDataGeneration() {
		return dataGenerationMethod;
	}

	public String getName() {
		return this.name;
	}

	public DataType getDataType() {
		return this.dataType;
	}

	public boolean isPrimaryKey() {
		return this.isPrimarykey;
	}

	public boolean isForeignKey() {
		return this.isForeignKey;
	}

	public String[] generateData(int numberOfLines){
		data = new String[numberOfLines];
		for (int i = 0; i < numberOfLines; i++) {
			data[i] = this.dataGenerationMethod.generate();
		}
		return data;
	}

	private boolean violateConstraint(String[] data) {
		if(this.isPrimaryKey() && hasDuplicateData(data)){
			return true;
		}
		return false;
	}
	

	private boolean hasDuplicateData(String[] data) {
		for(int i=0;i<data.length;i++){
			for(int j=i+1;j<data.length;j++){
				if(data[i].equals(data[j]))
					return true;
			}
		}
		return false;
	}

	public String[] getData() {
		return this.data;
	}

	public int getDataCount() {
		int counter = 0;
		for (int i = 0; i < data.length; i++) {
			if(data[i]!=null)
				counter ++;
		}
		return counter;
	}

}
